const https = require('https')
const querystring = require('querystring')

function httpsReq(method,url,data) {
  data = querystring.stringify(data)
  const host = url.split('/')[0]
  const path = url.split(host)[1]
  const options = {
    'method': method,
    'hostname': host,
    'path': path,
    'headers':{
      'Content-Type' : 'application/x-www-form-urlencoded',
      'Content-Length' : data.length,                        
    }
  }
  return new Promise(( resolve, reject ) => {
    const req = https.request(options, (res) => {
      const chunks = [];
      res.on("data", (chunk) => {
        chunks.push(chunk)
      })
      res.on("end", (chunk) => {
        const body = Buffer.concat(chunks);
        const result = JSON.parse(body.toString())
        resolve(result)
      })
      res.on("error", (error) => {
        reject(error)
      })
    })
    req.write(data);
    req.end()
  })
}

module.exports = {
  httpsReq
}

//const res = await http.httpsReq('get','galaha.top/api/Access/GetRec?pageSize=10')